//
//  ComposeViewController.swift
//  新浪微博
//
//  Created by 李赛 on 15/5/25.
//  Copyright (c) 2015年 李赛. All rights reserved.
//

import UIKit

class ComposeViewController: UIViewController , UITextViewDelegate{

    // 微博最大文本长度
    private let statusMaxLength = 140
    
    // 文本输入框
    @IBOutlet weak var textView: UITextView!
    // 姓名标签
    @IBOutlet weak var nameText: UILabel!
    // 工具栏底部约束
    @IBOutlet weak var toolBottomConstraint: NSLayoutConstraint!
    // 发送按钮
    @IBOutlet weak var sendBtn: UIBarButtonItem!
    
    @IBOutlet weak var pictureViewHeightConstraint: NSLayoutConstraint!
    
    // 图片选择控制器
    var pictureSelectVC : PictureSelectViewController?
    
    
    // 用代码向textView中添加一个标签
    lazy var placeholderLabel: UILabel = {
       let l = UILabel(frame: CGRectMake(5, 8, 0, 0))
        l.text = "分享新鲜事...."
        l.font = UIFont.systemFontOfSize(18)
        l.textColor = UIColor.lightGrayColor()
        l.sizeToFit()
        return l
    }()
    
    // 关闭按钮
    @IBAction func closeBtn(sender: UIBarButtonItem) {
        dismissViewControllerAnimated(true, completion: nil)
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        // 设置UI
        setupUI()
        
        //  注册通知
        regNotification()
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        if pictureSelectVC?.pictureList.count == 0 {
            // 获取焦点 激活键盘
            textView.becomeFirstResponder()
        }
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        // 关闭键盘
        textView.resignFirstResponder()
    }
    
    deinit {
        // 取消注册通知
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    private func setupUI() {
        
        for vc in childViewControllers {
            // 判断vc的类型 如果是图片视图
            if vc is PictureSelectViewController {
                pictureSelectVC = vc as? PictureSelectViewController
                break
            }
        }
        
        textView.addSubview(placeholderLabel)
        nameText.text = sharedUserAccount?.name
        textView.alwaysBounceVertical = true
        
        // 设置照片容器视图的高度
        pictureViewHeightConstraint.constant = 0
    }
    
    private func regNotification() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChanged:", name: UIKeyboardWillHideNotification, object: nil)
    }
    
    func keyboardChanged(notification : NSNotification) {
        println(notification)
        
        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
        // 键盘默认高度
        var height: CGFloat = 0
        // 判断是否边框变化事件
        if notification.name == UIKeyboardWillChangeFrameNotification {
            // 从userInfo 中取出键盘高度
            // 字典中保存的是结构体,通常是以NSValue格式保存
            let rect = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
            height = rect.height
        }
        
        UIView.animateWithDuration(duration, animations: { () -> Void in
            self.toolBottomConstraint.constant = height
            self.view.layoutIfNeeded()
        })
    }
    
    
    // MARK: textView 代理方法
    func textViewDidChange(textView: UITextView) {
        // 隐藏占位符
        placeholderLabel.hidden = !textView.text.isEmpty
        // 允许发送点击按钮
        sendBtn.enabled = !textView.text.isEmpty
        
    }
    
    func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
        if text == "\n"{
            println("回车")
        }
        
        // 判断字符串长度
        if count(textView.text) + count(text) > statusMaxLength {
            return false
        }
        return true
    }
    
    // 拖拽scrollView
    func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        //
        textView.resignFirstResponder()
    }
    
    @IBAction func sendMessage(sender: AnyObject) {
        
        let params = ["access_token" : sharedUserAccount?.access_token , "status" : textView.text]
        // 发送微博 需要判断是否有图片
        if pictureSelectVC?.pictureList.count > 0 {
            // 有图片
            let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            
            // 参数字典
            // 因为新浪微博第三方 只支持上传一张图片
            let image = pictureSelectVC?.pictureList[0]
            // png格式是无损压缩格式
            let data = UIImagePNGRepresentation(image)
            // key 是保存到服务器的文件名   value 是转化成二进制数据的图片
            let dataList = ["ooxx" : data]
            NetWorkTools.uploadPicture(urlString, fieldName: "pic", dataList: dataList, parameters: params)
            return
        }
        
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        NetWorkTools.requestJSON(.POST, URLString: urlString, parameters: params) { (json) -> () in
            println(json)
            self.dismissViewControllerAnimated(true, completion: nil)
        }
        
    }
    
    @IBAction func pictureSelect() {
        pictureViewHeightConstraint.constant = UIScreen.mainScreen().bounds.height / 3
        // 关闭键盘
        textView.resignFirstResponder()
        
    }
    
    
}
